package mz.matafe.bolao

import org.codehaus.groovy.grails.plugins.springsecurity.Secured

import grails.converters.JSON
//import grails.converters.deep.JSON

/**
 * Team Controller.
 *
 * <p>Handle the teams
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
class TeamController extends BolaoController{

    @Secured(['ROLE_USER'])
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    @Secured(['ROLE_USER'])
    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ teamList: Team.list( params ), teamTotal: Team.count() ]
    }

    @Secured(['ROLE_ADMIN','ROLE_SUPERVISOR'])
    def show = {
        def team = Team.get( params.id )
        if(!team) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'team.label', default: 'Team'), params.id])}"
            redirect(action:list)
        }
        else { 
            [ team : team ]
        }
    }

    @Secured(['ROLE_ADMIN'])
    def delete = {
        def team = Team.get( params.id )
        if(team) {
            def matches = Match.findAllByTeam1OrTeam2(team,team)
            if (!matches.isEmpty()){
                flash.message = "Existem jogos para este time. Favor apaga-los primeiro"
                redirect(action:show,id:params.id)
            }else{
                try {
                    team.delete(flush:true)
                    flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'team.label', default: 'Team'), params.id])}"
                    redirect(action:list)
                }
                catch(org.springframework.dao.DataIntegrityViolationException e) {
                    flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'team.label', default: 'Team'), params.id])}"
                    redirect(action:show,id:params.id)
                }
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'team.label', default: 'Team'), params.id])}"
            redirect(action:list)
        }
    }

    @Secured(['ROLE_ADMIN'])
    def edit = {
        def team = Team.get( params.id )

        if(!team) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'team.label', default: 'Team'), params.id])}"
            redirect(action:list)
        }
        else {
            return [ team : team ]
        }
    }

    @Secured(['ROLE_ADMIN'])
    def update = {
        def team = Team.get( params.id )
        if(team) {
            if(params.version) {
                def version = params.version.toLong()
                if(team.version > version) {
                    team.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'team.label', default: 'Team')] as Object[], "Another user has updated this Team while you were editing")
                    render(view:'edit',model:[team:team])
                    return
                }
            }

            def oldFlag = team.flagImage
            def f = request.getFile('flagImage')

            // List of OK mime-types
            def okcontents = ['image/png', 'image/jpeg', 'image/gif']
            if (!f.empty && !okcontents.contains(f.getContentType())) {
                flash.message = "O tipo da imagem deve ser: ${okcontents}"
                render(view:'edit',model:[team:team])
                return;
            }

            log.info("File uploaded: " + f.getContentType())

            team.properties = params

            if (f.empty){
                team.flagImage = oldFlag
            }

            if(!team.hasErrors() && team.save()) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'team.label', default: 'Team'), team.name])}"
                redirect(action:show,id:team.id)
            }
            else {
                render(view:'edit',model:[team:team])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'team.label', default: 'Team'), params.id])}"
            redirect(action:list)
        }
    }

    @Secured(['ROLE_ADMIN'])
    def create = {
        def team = new Team()
        team.properties = params
        return ['team':team]
    }

    @Secured(['ROLE_ADMIN'])
    def save = {
        def team = new Team(params)

        def f = request.getFile('flagImage')

        // List of OK mime-types
        def okcontents = ['image/png', 'image/jpeg', 'image/gif']
        if (!f.empty && !okcontents.contains(f.getContentType())) {
            flash.message = "O tipo da imagem deve ser: ${okcontents}"
            render(view:'create',model:[team:team])
            return;
        }

        log.info("File uploaded: " + f.getContentType())
        
        team.teamDetails = new TeamDetails(played:0,won:0,draw:0,
            lost:0,goalsFor:0,goalsAgainst:0,points:0)
        if(!team.hasErrors() && team.save()) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'team.label', default: 'Team'), team.name])}"
            redirect(action:show,id:team.id)
        }
        else {
            render(view:'create',model:[team:team])
        }
    }

    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def ajaxGetTeams = {
        def teams = null
        if (params.id != 'null'){
            def group = Group.get(params.id)
            teams = group?.teams
        }else{
            teams = Team.list()
        }
        render teams as JSON
    }

    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def renderFlagImage = {
        def team = Team.get(params.id)
        if (team?.flagImage) {
            response.setContentLength(team.flagImage.length)
            response.outputStream.write(team.flagImage)
        } else {
            //if no photo
            response.sendError(404)
        }
    }

}
